package com.example.resourceSharingPlatform.dao;

import com.example.resourceSharingPlatform.entity.User;
import com.example.resourceSharingPlatform.mappers.UserRowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据id查询user信息
     * parameter: int id
     * */
    public User queryUserById(String id){
        String sql = "SELECT * FROM user WHERE id=? ";
        User user = jdbcTemplate.queryForObject(sql, new UserRowMapper(), id);
        return user;
    }

    /**
     * 根据name查询user信息
     * parameter: String name
     * */
    public User queryUserByName(String name){
        String sql = "SELECT * FROM user WHERE name=? ";
        User user = jdbcTemplate.queryForObject(sql, new UserRowMapper(), name);
        return user;
    }

    /**
     * 查询所有user信息
     * none parameter
     * */
    public List<User> queryAll(){
        String sql = "SELECT * FROM user";
        List<User> userList = jdbcTemplate.query(sql, new UserRowMapper());
        return userList;
    }

    /**
     * 插入一条user信息
     * parameter: User user
     * */
    public User insertUser(User user){
        String sql = "INSERT INTO user VALUES(?,?,?,?,?,?)";
        updateByUser(sql,user);
        String sql2 = "SELECT * FROM user WHERE id=?";
        return jdbcTemplate.queryForObject(sql2,new UserRowMapper(),user.getId());
    }

    /**
     * 根据id删除一条user信息
     * parameter: User user
     * */
    public boolean deleteUserById(String id){
        String sql = "DELETE FROM user WHERE id=?";
        int row = jdbcTemplate.update(sql,id);
        return row!= 0;
    }

    /**
     * 根据User的id更新一条user信息
     * parameter: User user
     * */
    public boolean updateUser(User user){
        String sql = "UPDATE user SET id=?, name=?, photo=?, gender=?, age=?, tel=? " +
                "WHERE id ="+user.getId();
        int row = updateByUser(sql, user);
        return row != 0;
    }

    private int updateByUser(String sql, User user){
        return jdbcTemplate.update(sql,user.getId(),user.getName(),user.getPhoto(),user.getGender(),user.getAge(),user.getTel());
    }

}
